package utils

import (
	"barrage-go/db"
	"context"
	"log"
	"time"
)

var ctx = context.Background()

func Set(key string, value string) {
	SetExp(key, value, 0)
}

func SetExp(key string, value string, exp time.Duration) {
	rdb := db.GetRedis()
	err := rdb.Set(ctx, key, value, exp).Err()
	if err != nil {
		log.Panicln("redis设置过期时间数据异常:", err)
	}
}

func Get(key string) string {
	rdb := db.GetRedis()
	val, err := rdb.Get(ctx, key).Result()
	if err != nil {
		log.Println("redis获取数据异常:", err)
		val = "0"
	}
	return val
}

func Incr(key string) int64 {
	rdb := db.GetRedis()
	num, err := rdb.Incr(ctx, key).Result()
	if err != nil {
		log.Panicln("redis设置自增异常:", err)
	}
	return num
}

func Decr(key string) {
	rdb := db.GetRedis()
	_, err := rdb.Decr(ctx, key).Result()
	if err != nil {
		log.Panicln("redis设置自减少异常:", err)
	}
}
